import twitter
from urllib2 import HTTPError

from rctk.widgets import Window, StaticText, Text, Button, Panel, Password
from rctk.layouts import Grid, VBox, StaticVBox

def unescape(s): 
    """ unescape &lt; etc, StaticText does its own """
    return s.replace("&lt;", "<").replace("&gt;", ">").replace("&amp;", "&")

class LoginDialog(Window):
    def __init__(self, parent, tk):
        super(LoginDialog, self).__init__(tk, title="Login", modal=True)
        self.parent = parent
        self.setLayout(Grid(columns=2))
        
        self.alert = StaticText(self.tk, "", height=40, foreground="#ff0000")
        self.append(self.alert, colspan=2)

        self.append(StaticText(self.tk, "Username"))
        self.username = Text(self.tk)
        self.append(self.username)

        self.append(StaticText(self.tk, "Password"))
        self.password = Password(self.tk)
        self.append(self.password)

        self.append(StaticText(self.tk, ""))
        login = Button(self.tk, "Login")
        self.append(login)

        login.click = self.login
        self.layout()

    def login(self, event):
        try:
            username = self.username.value
            password = self.password.value

            api = twitter.Api(username=username, password=password)
            api.GetFriendsTimeline(username)
            self.close()
            self.parent.loggedin(api, username, password)
        except HTTPError, e:
            self.alert.text = "Invalid username or password"
            
class TsjilpUI(object):
    def __init__(self, parent, tk, username):
        self.tk = tk
        self.parent = parent
        self.win = tk.root()
        self.win.setLayout(VBox())
        self.activity = Panel(self.tk, width=300, height=450, scrolling=True)
        self.activity.setLayout(VBox())
        ## cannot be empty, see issue 8
        self.activity.append(StaticText(tk, "Welcome to Tsjilp!..."))
        self.win.append(self.activity)
        self.status = Text(self.tk)
        self.status.submit = self.submit_status
        self.win.append(self.status)
        self.win.layout()

    def add_tweet(self, user, screen, text):
        l = StaticText(self.tk, "%s (%s)" % (user, screen), bold=True)
        e = StaticText(self.tk, unescape(text), wrap=True)
        self.activity.append(l)
        self.activity.append(e)
        self.win.layout()

    def submit_status(self, event):
        status = self.status.value.strip()
        if status:
            self.parent.status_update(status)
        self.status.value = ""

class Tsjilp(object):
    def __init__(self):
        self.since_id = None
        self.interval = 300 # 5 minutes

    def loggedin(self, api, username, password):
        self.api = api
        self.username = username
        self.w = TsjilpUI(self, self.tk, username)
        self.update()

    def status_update(self, status):
        self.api.PostUpdate(status)

    def update(self):
        statuses = self.api.GetFriendsTimeline(self.username, since_id=self.since_id)
        if self.since_id is None: ## first run
            statuses = statuses[:15]
        statuses = list(statuses)
        for s in reversed(statuses):
            self.w.add_tweet(s.user.name, s.user.screen_name, s.text)
        if statuses:
            self.since_id = statuses[0].id
        self.tk.set_timer(lambda event: self.update(), self.interval * 1000)

    def run(self, tk):
        self.tk = tk
        LoginDialog(self, tk)

def main():
    """ for standalone running """
    from rctk.webpy import serve
    from rctk.sessions import Session, Manager
    import os

    manager = Manager(Session, Tsjilp, os.getcwd())
    serve(manager)
 

